package cn.liuhuan1.mongoDb.fastDfsConfig;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.IOException;

/**
 * @author 28067
 * @Auther: liuhuan
 * @Date: 2021/4/7 - 04 - 07 - 19:34
 * @Description:
 * @version: 1.0
 */
@Configuration
@PropertySource("classpath:/fastDfsConfig.properties")
public class StorageClientConfig {
    private static final Logger logger = LoggerFactory.getLogger(StorageClientConfig.class);

    @Value("${fastdfs.connectTimeout}")
    private Integer connectTimeout;

    @Value("${fastdfs.server.ip}")
    private String ip;

    @Value("${fastdfs.trackerServer}")
    private String  trackerServer;

    @Value("${fastdfs.trackerHttpPort}")
    private Integer trackerHttpPort;

    @Value("${fastdfs.networkTimeout}")
    private Integer networkTimeout;

    @Bean
    public StorageClient storageClient() throws IOException, MyException {
        this.initClientGlobal();

        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
        return new StorageClient(trackerServer, storageServer);
    }

    private void initClientGlobal() throws IOException, MyException {
        ClientGlobal.initByTrackers(trackerServer);

        if(trackerHttpPort !=null && trackerHttpPort.intValue()!=0) {
            ClientGlobal.setG_tracker_http_port(trackerHttpPort);
        }

        if(connectTimeout != null && connectTimeout.intValue() != 0) {
            ClientGlobal.setG_connect_timeout(connectTimeout);
        }
        if(networkTimeout!=null && networkTimeout.intValue()!=0) {
            ClientGlobal.setG_network_timeout(networkTimeout);
        }
    }

}
